<?php

class Dcmp_Web_Identity extends Kd_Web_Identity {

    public function __construct() {	
        parent::__construct();
    }
    
    public function getIsBackendUser(){
    	return $this->data['backendUser'];
    }
    
    public function setIsBackendUser($value){
    	$this->data['backendUser'] = $value;
    	return $this;
    }

    public function isSuperAdmin() {
        return $this->data['grade'] == 'sa';
    }

    public function getGrade() {
        return $this->data['grade'];
    }

    public function setGrade($value) {
        $this->data['grade'] = $value;
        return $this;
    }
    
    public function addRoleIds(array $ids){
    	if(!array_key_exists('roleids', $this->data)){
    		$this->data['roleids'] = array();
    	}
    	$this->data['roleids'] = array_merge($this->data['roleids'], $ids);
    	return $this;
    }
    
    public function getRoleIds(){
    	if(array_key_exists('roleids', $this->data)){
    		return $this->data['roleids'];
    	}
    	return NULL;
    }    

    public function getRoles() {
        $args = func_get_args();
        $result = array();
        if (func_num_args () == 0) {
        	return $this->data['roles'];
        } else {
        	$roles = $this->data['roles'][$args[0]];
        	foreach ($roles as $role) {
        		$result[] = $args[0] . '_' . $role;
        	}
        }
        return $result;
    }
    
    public function addRole($role) {
        $roles = Kd_Util_Array::pack($role);
        foreach ($roles as $role){
        	$arr = explode('_', $role);
        	if (!array_key_exists($arr[0], $this->data['roles'])) {
        		$this->data['roles'][$arr[0]] = array();
        	}
        	$this->data['roles'][$arr[0]][] = $arr[1];
        }
        return $this;
    }

    public function isInRole($role) {
        if ($this->isSuperAdmin()) {
            return TRUE;
        }
        $arr =explode('_', $role);
        foreach ($this->data['roles'] as $name => $roles) {
            if ($name == $arr[0]) {
                if (in_array($arr[1], $roles)) {
                    return TRUE;
                }
            }
        }
        return FALSE;
    }

    public function isInAnyRole(array $roles) {
        foreach ($roles as $role) {
            if ($this->isInRole($role)) {
                return TRUE;
            }
        }
        return FALSE;
    }    

	public function isAllowAction($action){
        if ($this->isSuperAdmin()) {
            return TRUE;
        }
        return parent::isAllowAction($action);		
	}
}